﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infrastructure;
using DBDataAccessLib.DataMapping;
using System.Collections.ObjectModel;
using Microsoft.Practices.Prism.Commands;
using System.Threading;
using DBDataAccessLib;
using System.IO;
using PluginManager;
using Infrastructure.Events;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.ServiceLocation;
using System.ComponentModel;

namespace UserControlLib
{
    public class MachineInfoControlViewModel : ViewModelBase
    {
        private ManualResetEvent mre = new ManualResetEvent(true);

        public MachineInfoControlViewModel()
        {
            SaveCommand = new DelegateCommand<object>(OnSaveCommand, OnCanSaveCommand);
            SimilarCommand = new DelegateCommand<object>(OnSimilarCommand, OnCanSimilarCommand);
            SetValues();
        }

        public void OnSimilarCommand(object obj)
        {
            MachineInfoRecordMapping record = MachineInfoDataAccess.GetMachineInfoByPrimKey(WCNO, SelectedStationName, Model, 0);
            string[] imagePaths = record.Essentials.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in imagePaths)
            {
                foreach (var image in ImageList)
                {
                    if (image.ImagePath == item)
                    {
                        image.IsChecked = true;
                        break;
                    }
                }
            }
        }

        public bool OnCanSimilarCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(WCNO) && !string.IsNullOrWhiteSpace(SelectedStationName) &&
                !string.IsNullOrWhiteSpace(Model);
        }

        private void SetValues()
        {
            this.IsBusy = true;
            MessageContent = "正在获取工位信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                mre.Reset();
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> wcnos = StationNameDataAccess.GetAllWCNOLines().ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.WCNOLines = p as ObservableCollection<string>;
                    if (WCNOLines.Count > 0 && !IsEditMode) this.WCNO = this.WCNOLines.First();
                    mre.Set();
                }), wcnos);
            }), SynchronizationContext.Current);
        }

        public void OnSaveCommand(object obj)
        {
            this.IsBusy = true;
            MessageContent = "正在保存...";
            bool isSuccess = false;
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                string essentials = string.Empty;
                SynchronizationContext context = currentContext as SynchronizationContext;

                MachineInfoRecordMapping record = MachineInfoDataAccess.GetMachineInfoByPrimKey(WCNO, SelectedStationName, Model, 0);
                if (!IsEditMode)
                {
                    if (record == null)
                    {
                        IEnumerable<ImageListModel> li = ImageList.Where(p => p.IsChecked);
                        foreach (var item in li)
                        {
                            essentials += item.ImagePath + "|";
                        }

                        int val = MachineInfoDataAccess.AddMachineInfo(WCNO, SelectedStationName, Model, Sebango, 0, essentials, string.IsNullOrWhiteSpace(CycleTime) ? "" : CycleTime, (GeneralInformation.ViewStates["UserInfo"] as AccountMapping).UserName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        if (val > 0) isSuccess = true;
                        else isSuccess = false;
                    }
                }
                else
                {
                    if (record == null) isSuccess = false;
                    else
                    {
                        IEnumerable<ImageListModel> li = ImageList.Where(p => p.IsChecked);
                        foreach (var item in li)
                        {
                            essentials += item.ImagePath + "|";
                        }

                        int val = MachineInfoDataAccess.UpdateMachineInfo(WCNO, SelectedStationName, Model, Sebango, essentials, string.IsNullOrWhiteSpace(CycleTime) ? "" : CycleTime, (GeneralInformation.ViewStates["UserInfo"] as AccountMapping).UserName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        if (val > 0) isSuccess = true;
                        else isSuccess = false;
                    }
                }
                context.Send(new SendOrPostCallback(p =>
                 {
                     IsBusy = false;
                     if (!IsEditMode)
                     {
                         if (isSuccess) ModalWindowService.ShowMessage("添加成功。");
                         else ModalWindowService.ShowMessage("添加失败。");
                     }
                     else
                     {
                         if (!isSuccess) ModalWindowService.ShowMessage("添加失败。");
                         else ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<EditAccomplished>().Publish(null);
                     }
                 }), null);
            }), SynchronizationContext.Current);

        }

        public bool OnCanSaveCommand(object obj)
        {
            return !string.IsNullOrWhiteSpace(WCNO) && !string.IsNullOrWhiteSpace(Sebango) && !string.IsNullOrWhiteSpace(Model) &&
                !string.IsNullOrWhiteSpace(SelectedStationName) && !string.IsNullOrWhiteSpace(CycleTime) && !HasErrors;
        }

        public DelegateCommand<object> SaveCommand { get; set; }
        public DelegateCommand<object> SimilarCommand { get; set; }

        private bool isEditMode;

        public bool IsEditMode
        {
            get { return isEditMode; }
            set
            {
                isEditMode = value;
                IsEnabled = !value;
            }
        }

        private MachineInfoRecordMapping machineInfo;

        public MachineInfoRecordMapping MachineInfo
        {
            get { return machineInfo; }
            set
            {
                if (machineInfo != value)
                {
                    machineInfo = value;
                    OnPropertyChanged("MachineInfo");
                    if (machineInfo != null)
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                           {
                               if (mre.WaitOne())
                               {
                                   (currentContext as SynchronizationContext).Send(new SendOrPostCallback(p =>
                                       {
                                           SetInitialValues();
                                       }), null);
                               }
                           }), SynchronizationContext.Current);
                    }
                }
            }
        }

        private void SetInitialValues()
        {
            this.WCNO = MachineInfo.WCNO;
            this.Model = MachineInfo.Model;
            this.Sebango = MachineInfo.Sebango;
            this.CycleTime = MachineInfo.CycleTime;
        }

        private bool isEnabled;

        public bool IsEnabled
        {
            get { return isEnabled; }
            set
            {
                isEnabled = value;
                OnPropertyChanged("IsEnabled");
            }
        }

        //private string wcnoSimilar;

        //public string WCNOSimilar
        //{
        //    get { return wcnoSimilar; }
        //    set
        //    {
        //        if (wcnoSimilar != value)
        //        {
        //            wcnoSimilar = value.Trim();
        //            OnPropertyChanged("WCNOSimilar");
        //            FillStationNamesSimilar(value);
        //            SimilarCommand.RaiseCanExecuteChanged();
        //        }
        //    }
        //}

        //private void FillStationNamesSimilar(string value)
        //{
        //    this.IsBusy = true;
        //    MessageContent = "正在获取工位信息...";
        //    ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
        //    {
        //        SynchronizationContext context = currentContext as SynchronizationContext;
        //        ObservableCollection<string> stations = StationNameDataAccess.GetAllStationNames(value).ToObservableCollection();
        //        context.Send(new SendOrPostCallback(p =>
        //        {
        //            IsBusy = false;
        //            this.StationNamesSimilar = p as ObservableCollection<string>;
        //            if (this.StationNames.Count > 0) this.StationNameSimilar = this.StationNames.First();
        //        }), stations);
        //    }), SynchronizationContext.Current);
        //}

        //private string stationNameSimilar;

        //public string StationNameSimilar
        //{
        //    get { return stationNameSimilar; }
        //    set
        //    {
        //        if (stationNameSimilar != value)
        //        {
        //            stationNameSimilar = value;
        //            OnPropertyChanged("StationNameSimilar");
        //            SimilarCommand.RaiseCanExecuteChanged();
        //        }
        //    }
        //}

        //private string modelSimilar;

        //public string ModelSimilar
        //{
        //    get { return modelSimilar; }
        //    set
        //    {
        //        modelSimilar = value;
        //        OnPropertyChanged("ModelSimilar");
        //        SimilarCommand.RaiseCanExecuteChanged();
        //    }
        //}


        //private ObservableCollection<string> stationNamesSimilar;

        //public ObservableCollection<string> StationNamesSimilar
        //{
        //    get { return stationNamesSimilar; }
        //    set
        //    {
        //        stationNamesSimilar = value;
        //        OnPropertyChanged("StationNamesSimilar");
        //    }
        //}


        private string wcno;

        public string WCNO
        {
            get { return wcno; }
            set
            {
                if (wcno != value)
                {
                    wcno = value.Trim();
                    OnPropertyChanged("WCNO");
                    FillStationNames(value);
                    SaveCommand.RaiseCanExecuteChanged();
                    SimilarCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private void FillStationNames(string wcno)
        {
            this.IsBusy = true;
            MessageContent = "正在获取工位信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> stations = StationNameDataAccess.GetAllStationNames(wcno).ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.StationNames = p as ObservableCollection<string>;
                    if (IsEditMode && MachineInfo != null)
                    {
                        this.SelectedStationName = MachineInfo.StationName;
                    }
                    else
                    {
                        if (this.StationNames.Count > 0) this.SelectedStationName = this.StationNames.First();
                    }
                }), stations);
            }), SynchronizationContext.Current);
        }

        private ObservableCollection<string> stationNames;

        public ObservableCollection<string> StationNames
        {
            get { return stationNames; }
            set
            {
                stationNames = value;
                OnPropertyChanged("StationNames");
            }
        }

        private string selectedStationName;

        public string SelectedStationName
        {
            get { return selectedStationName; }
            set
            {
                if (selectedStationName != value)
                {
                    selectedStationName = value;
                    OnPropertyChanged("SelectedStationName");
                    FillImageList(value);
                    SaveCommand.RaiseCanExecuteChanged();
                    SimilarCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private void FillImageList(string stationName)
        {
            this.IsBusy = true;
            MessageContent = "正在获取图片信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<ImageListModel> models = new ObservableCollection<ImageListModel>();
                if (Directory.Exists(Helper.ServerUrl + WCNO + "\\" + stationName))
                {
                    foreach (var path in Directory.GetFiles(Helper.ServerUrl + WCNO + "\\" + stationName))
                    {
                        FileInfo info = new FileInfo(path);
                        if (info.Extension.ToLower() == ".jpg" || info.Extension.ToLower() == ".jpeg")
                        {
                            models.Add(new ImageListModel { ImagePath = info.Name, FullPath = path, IsChecked = false });
                        }
                    }
                }
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.ImageList = p as ObservableCollection<ImageListModel>;
                    if (IsEditMode && MachineInfo != null)
                    {
                        string[] imagePaths = MachineInfo.Essentials.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var item in ImageList)
                        {
                            foreach (var path in imagePaths)
                            {
                                if (item.ImagePath == path)
                                {
                                    item.IsChecked = true;
                                    break;
                                }
                            }
                        }
                    }
                }), models);
            }), SynchronizationContext.Current);
        }

        private string model;

        public string Model
        {
            get { return model; }
            set
            {
                model = value.Trim();
                CheckSebangoModel();
                SaveCommand.RaiseCanExecuteChanged();
                SimilarCommand.RaiseCanExecuteChanged();
            }
        }

        private string sebango;

        public string Sebango
        {
            get { return sebango; }
            set
            {
                if (sebango != value)
                {
                    sebango = value.Trim();
                    CheckSebangoModel();
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private void CheckSebangoModel()
        {
            if (string.IsNullOrWhiteSpace(Sebango) || string.IsNullOrWhiteSpace(Model)) return;
            RemoveError("Sebango");
            RemoveError("Model");

            if (SebangoMapping.Sebangos.FirstOrDefault(p => (p.Val1 == Sebango && p.Val2 == Model)) == null)
            {
                AddError("Sebango", "背番号和机种名不匹配");
                AddError("Model", "背番号和机种名不匹配");
            }
            OnPropertyChanged("Sebango");
            OnPropertyChanged("Model");
        }

        private string cycleTime;

        public string CycleTime
        {
            get { return cycleTime; }
            set
            {
                int v;
                if (int.TryParse(value.Trim(), out v))
                {
                    cycleTime = v.ToString();
                }
                else cycleTime = string.Empty;
                OnPropertyChanged("CycleTime");
                SaveCommand.RaiseCanExecuteChanged();
            }
        }

        private ObservableCollection<ImageListModel> imageList;

        public ObservableCollection<ImageListModel> ImageList
        {
            get { return imageList; }
            set
            {
                imageList = value;
                OnPropertyChanged("ImageList");
            }
        }

        private string selectedImage;

        public string SelectedImage
        {
            get { return selectedImage; }
            set
            {
                if (selectedImage != value)
                {
                    selectedImage = value;
                    OnPropertyChanged("SelectedImage");
                }
            }
        }

        private ImageListModel selectedImageModel;

        public ImageListModel SelectedImageModel
        {
            get { return selectedImageModel; }
            set
            {
                selectedImageModel = value;
                if (value != null) SelectedImage = value.FullPath;
                OnPropertyChanged("SelectedImageModel");
            }
        }

        private ObservableCollection<string> wcnoLines;

        public ObservableCollection<string> WCNOLines
        {
            get { return wcnoLines; }
            set
            {
                wcnoLines = value;
                OnPropertyChanged("WCNOLines");
            }
        }
    }

    public class ImageListModel : ViewModelBase
    {
        private bool isChecked;

        public bool IsChecked
        {
            get { return isChecked; }
            set
            {
                isChecked = value;
                OnPropertyChanged("IsChecked");
            }
        }

        private string imagePath;

        public string ImagePath
        {
            get { return imagePath; }
            set { imagePath = value; }
        }

        private string fullPath;

        public string FullPath
        {
            get { return fullPath; }
            set { fullPath = value; }
        }


    }
}
